#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string>
#include <vector>
#include <iostream>

int main () {
    int world_size = 4;
    std::vector<pid_t> pids(world_size); 
    for (int rank = 0; rank < world_size; rank ++) {
        std::string str_rank = std::to_string(rank);
        std::string str_world_size = std::to_string(world_size);
        setenv("MASTER_ADDR", "127.0.0.1", 1);
        setenv("MASTER_PORT", "9960", 1);
        setenv("RANK", str_rank.c_str(), 1);
        setenv("WORLD_SIZE", str_world_size.c_str(), 1);
        pid_t pid = fork();
        if (pid == 0) {
            std::cout << "pid: " << pid << ", rank: " << getenv("RANK") << ", world_size: " << getenv("WORLD_SIZE") << std::endl;
            return 0;
        } else if (pid < 0) {
            std::cerr << "fork failed, reason: " << strerror(errno) << std::endl;
            return pid;
        }
        pids[rank] = pid;
    }

    int status;
    for (int i = 0; i < world_size; i ++) {
        waitpid(pids[i], &status, 0);
        if (status != 0) {
            for (int j = i + 1; j < world_size; j ++) {
                kill(pids[j], SIGSTOP);
            }
            return status;
        }
    }
    std::cout << "I am parent process." << std::endl;
}
